package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.dao.BspsManagerInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsMchntApplyMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsManagerInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntApplyMapperImpl;
import cc.rengu.igas.bsps.common.entity.ManagerInfo;
import cc.rengu.igas.bsps.common.entity.MchntApplyInfo;
import cc.rengu.igas.bsps.common.enums.MchntApplyStatusEnum;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.service.base.BankManagerService;
import cc.rengu.igas.bsps.facade.request.MchntExpandAcceptRequest;
import cc.rengu.igas.bsps.facade.response.MchntExpandAcceptResponse;
import cc.rengu.igas.channel.wechat.facade.base.Header;
import cc.rengu.igas.channel.wechat.facade.request.MchntApplyAcceptMsgPushRequest;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;

/**
 * 商户入驻受理
 * @author zhangxuran
 * @version 1.0
 * @date 2020/04/07
 */
public class MchntExpandAcceptService extends BankManagerService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        MchntExpandAcceptRequest mchntExpandAcceptRequest = new MchntExpandAcceptRequest();
        ConvertUtil.convertOutput(mchntExpandAcceptRequest);
        return mchntExpandAcceptRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        MchntExpandAcceptRequest mchntExpandAcceptRequest = (MchntExpandAcceptRequest) request;
        MchntExpandAcceptResponse mchntExpandAcceptResponse = new MchntExpandAcceptResponse();
        /*获取上送报文参数信息：法人行号，拓展经理openId，拓展经理工号，申请单号，商户openId*/
        String instId = mchntExpandAcceptRequest.getHeader().getInstId();
        String userId = mchntExpandAcceptRequest.getUserId();
        String managerId = mchntExpandAcceptRequest.getManagerId();
        String applyId = mchntExpandAcceptRequest.getApplyId();
        String acceptStatus = mchntExpandAcceptRequest.getAcceptStatus();
        String acceptDesc = mchntExpandAcceptRequest.getAcceptDesc();
        /*10-申请单已受理, 20-申请单已入驻 */
        acceptStatus = StringUtil.isEmptyOrNull(acceptStatus) ? "10" : acceptStatus;
        /*必填校验*/
        if (StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(managerId) || StringUtil.isEmptyOrNull(applyId) || StringUtil.isEmptyOrNull(instId)) {
            rglog.error("请求参数校验必填字段失败,userId:<{}>,managerId:<{}>,applyId:<{}>,instId:<{}>", userId, managerId, applyId, instId);
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /*1-更新商户申请信息数据*/
        BspsMchntApplyMapper bspsMchntApplyMapper = new BspsMchntApplyMapperImpl();
        MchntApplyInfo mchntApplyInfo = bspsMchntApplyMapper.selectBspsMchntApplyInfoByPrimaryKey(instId, applyId);
        if (null == mchntApplyInfo) {
            rglog.error("商户申请信息查询失败！");
            throw new BizException(RespCodeEnum.GET_APPLY_INFO_ERROR.getRespCode(), RespCodeEnum.GET_APPLY_INFO_ERROR.getRespDesc());
        }
        if (MchntApplyStatusEnum.EXPANDED.getApplyStatus().equals(mchntApplyInfo.getApplyStatus())) {
            rglog.error("商户申请已入驻");
            throw new BizException(RespCodeEnum.MCHNT_APPLY_DONE_ERROR.getRespCode(), RespCodeEnum.MCHNT_APPLY_DONE_ERROR.getRespDesc());
        }
        //当已经是受理状态，再次来调整受理状态时报错
        if ("10".equals(acceptStatus)) {
            if (MchntApplyStatusEnum.ACCEPTED.getApplyStatus().equals(mchntApplyInfo.getApplyStatus()) || MchntApplyStatusEnum.EXPANDED.getApplyStatus().equals(mchntApplyInfo.getApplyStatus())) {
                rglog.error("商户申请已受理");
                throw new BizException(RespCodeEnum.MCHNT_APPLY_DONE_ERROR.getRespCode(), RespCodeEnum.MCHNT_APPLY_DONE_ERROR.getRespDesc());
            }
        }
        if ("20".equals(acceptStatus)) {
            if (MchntApplyStatusEnum.EXPANDED.getApplyStatus().equals(mchntApplyInfo.getApplyStatus()) || MchntApplyStatusEnum.APPLYING.getApplyStatus().equals(mchntApplyInfo.getApplyStatus())) {
                rglog.error("商户申请已入驻");
                throw new BizException(RespCodeEnum.MCHNT_APPLY_DONE_ERROR.getRespCode(), RespCodeEnum.MCHNT_APPLY_DONE_ERROR.getRespDesc());
            }
        }
        /*拓展经理信息查询*/
        BspsManagerInfoMapper bspsManagerInfoMapper = new BspsManagerInfoMapperImpl();
        rglog.info("拓展经理openId：" + mchntExpandAcceptRequest.getUserId());
        ManagerInfo managerInfo = null;
        if ("APP".equals(mchntExpandAcceptRequest.getHeader().getChanlId())){
            managerInfo = bspsManagerInfoMapper.selectBspsManagerInfoById(instId,mchntExpandAcceptRequest.getUserId());
        }else {
            managerInfo = bspsManagerInfoMapper.selectBspsManagerInfoByOpenId(instId, mchntExpandAcceptRequest.getUserId());
        }
        if (null == managerInfo) {
            rglog.error("拓展经理信息查询失败！");
            throw new BizException(RespCodeEnum.GET_MANAGER_INFO_ERROR.getRespCode(), RespCodeEnum.GET_MANAGER_INFO_ERROR.getRespDesc());
        }
        /*商户申请信息更新赋值*/
        /*拓展经理工号*/
        mchntApplyInfo.setManagerId(managerInfo.getManagerId());
        /*拓展经理姓名赋值*/
        mchntApplyInfo.setManagerName(managerInfo.getManagerName());
        /*拓展经理手机号*/
        mchntApplyInfo.setManagerPhone(managerInfo.getManagerPhone());
        /*拓展经理受理时间赋值*/
        mchntApplyInfo.setAcceptTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        /*受理状态赋值*/
        //mchntApplyInfo.setApplyStatus(MchntApplyStatusEnum.ACCEPTED.getApplyStatus());

        mchntApplyInfo.setApplyStatus(acceptStatus);
        mchntApplyInfo.setApplyResult(acceptDesc);

        /*更新商户申请信息操作*/
        int iReturnCode = bspsMchntApplyMapper.updateBspsMchntApplyInfoByPrimaryKey(mchntApplyInfo);
        if (0 != iReturnCode) {
            rglog.error("商户申请拓展经理受理失败！");
            throw new BizException(RespCodeEnum.UPDATE_APPLY_INFO_ERROR.getRespCode(), RespCodeEnum.UPDATE_APPLY_INFO_ERROR.getRespDesc());
        }
        if (!"20".equals(acceptStatus) && !"30".equals(acceptStatus)) {
            /*2-拓展经理受理后需要异步商户发送消息推送*/
            //获取通道标识,设置通道标识（需要修改，通道标识和通道序号，这个是从交易码映射表中获取）
            /* 调用dobbu服务*/
            XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
            DubboService dubboService = new DubboServiceImpl();
            /*异步消息推送请求报文信息拼装*/
            MchntApplyAcceptMsgPushRequest mchntApplyAcceptMsgPushRequest = new MchntApplyAcceptMsgPushRequest();
            Header header = new Header();

            header.setInstId(instId);
            header.setSrcSysId(AppParamConstant.SYS_ID);
            header.setChanlId(ChannelEnum.BSPS.getChannelType());
            header.setBizType("00");
            header.setVersion("1.0.0");
            header.setTransDate(DateUtil.getCurrentDate());
            header.setTransTime(DateUtil.getCurrentTime());
            header.setTxnNum("applyaccept");
            header.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM));
            mchntApplyAcceptMsgPushRequest.setHeader(header);
            /* 渠道标识赋值*/
            mchntApplyAcceptMsgPushRequest.setChannelId(ChannelEnum.WXZF.getChannelType());
            /*商户openId赋值*/
            mchntApplyAcceptMsgPushRequest.setOpenId(mchntApplyInfo.getOpenId());
            /*拓展经理姓名赋值*/
            mchntApplyAcceptMsgPushRequest.setAcceptName(managerInfo.getManagerName());
            /*拓展经理手机号赋值*/
            mchntApplyAcceptMsgPushRequest.setPhoneNo(managerInfo.getManagerPhone());

            /*需要配置异步服务*/
            dubboService.asynCallDubboService("wechatMsgPushService", "mchntApplyAcceptMsgPush", mchntApplyAcceptMsgPushRequest, null);
        }
        /*拼装返回报文信息*/
        BizResponse<MchntExpandAcceptResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(mchntExpandAcceptResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MchntExpandAcceptResponse mchntExpandAcceptResponse = (MchntExpandAcceptResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mchntExpandAcceptResponse);
    }
}
